package com.lc.user.express.utils;

import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.lc.user.express.MainActivity;
import com.lc.user.express.app.AppContext;
import com.lc.user.express.httpserver.GetCityId;
import com.lc.user.express.my.MyStardandActivity;
import com.lc.user.express.ordering.OrderingFragment;
import com.lc.user.express.ordering.SelectCityActivity;
import com.zcx.helper.http.AsyCallBack;

/**
 * Created by Administrator on 2016/4/20.
 */
public class LocationUtils {
    private AMapLocationClient locationClient = null;
    private AMapLocationClientOption locationOption = null;
    public double lat;
    public double lng;

    private static class LocationHolder {
        private static LocationUtils instance = new LocationUtils();
    }

    /**
     * 私有的构造函数
     */
    public LocationUtils() {

    }

    public static LocationUtils getInstance() {
        return LocationHolder.instance;
    }

    public void method() {
        System.out.println("LocationUtils");
    }

    private Object readResolve() {
        return getInstance();
    }

    /**
     * 定位初始化
     */
    public void init() {
        initOption();
        // 设置定位监听
        locationClient.setLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                if (null != aMapLocation) {
                    Message msg = mHandler.obtainMessage();
                    msg.obj = aMapLocation;
                    msg.what = MSG_LOCATION_FINISH;
                    mHandler.sendMessage(msg);
                }
            }
        });
        // 设置定位参数
        locationClient.setLocationOption(locationOption);
        // 启动定位
        locationClient.startLocation();
    }

    Handler mHandler = new Handler() {
        public void dispatchMessage(Message msg) {
            switch (msg.what) {
                //开始定位
                case MSG_LOCATION_START:
//                    tvReult.setText("正在定位...");
                    break;
                // 定位完成
                case MSG_LOCATION_FINISH:
                    AMapLocation loc = (AMapLocation) msg.obj;
                    String result = getLocationStr(loc);
                    Logger.print("lll", "result=" + result);
//                    tvReult.setText(result);
                    break;
                //停止定位
                case MSG_LOCATION_STOP:
//                    tvReult.setText("定位停止");
                    break;
                default:
                    break;
            }
        }

        ;
    };

    private void initOption() {
        locationClient = new AMapLocationClient(AppContext.getContext());
        locationOption = new AMapLocationClientOption();
        // 设置定位模式为高精度模式
        locationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        locationOption.setOnceLocation(false);
        // 设置是否需要显示地址信息
        locationOption.setNeedAddress(true);


        /**
         * 设置是否优先返回GPS定位结果，如果30秒内GPS没有返回定位结果则进行网络定位
         * 注意：只有在高精度模式下的单次定位有效，其他方式无效
         */
        locationOption.setGpsFirst(true);

        locationOption.setInterval(60000);

    }

    /**
     * 开始定位
     */
    public final static int MSG_LOCATION_START = 0;
    /**
     * 定位完成
     */
    public final static int MSG_LOCATION_FINISH = 1;
    /**
     * 停止定位
     */
    public final static int MSG_LOCATION_STOP = 2;


    public synchronized String getLocationStr(AMapLocation location) {
        if (null == location) {
            return null;
        }
        StringBuffer sb = new StringBuffer();
        //errCode等于0代表定位成功，其他的为定位失败，具体的可以参照官网定位错误码说明
        if (location.getErrorCode() == 0) {
            sb.append("定位成功" + "\n");
            sb.append("定位类型: " + location.getLocationType() + "\n");
            sb.append("经    度    : " + location.getLongitude() + "\n");
            sb.append("纬    度    : " + location.getLatitude() + "\n");
            sb.append("精    度    : " + location.getAccuracy() + "米" + "\n");
            sb.append("提供者    : " + location.getProvider() + "\n");

            if (location.getProvider().equalsIgnoreCase(
                    android.location.LocationManager.GPS_PROVIDER)) {
                // 以下信息只有提供者是GPS时才会有
                sb.append("速    度    : " + location.getSpeed() + "米/秒" + "\n");
                sb.append("角    度    : " + location.getBearing() + "\n");
                // 获取当前提供定位服务的卫星个数
                sb.append("星    数    : "
                        + location.getSatellites() + "\n");
            } else {
                // 提供者是GPS时是没有以下信息的
                sb.append("国    家    : " + location.getCountry() + "\n");
                sb.append("省            : " + location.getProvince() + "\n");
                sb.append("市            : " + location.getCity() + "\n");
                sb.append("城市编码 : " + location.getCityCode() + "\n");
                sb.append("区            : " + location.getDistrict() + "\n");
                sb.append("区域 码   : " + location.getAdCode() + "\n");
                sb.append("地    址    : " + location.getAddress() + "\n");
                sb.append("兴趣点    : " + location.getPoiName() + "\n");
                sb.append("街:" + location.getStreet() + location.getStreetNum());

            }
        } else {
            //定位失败
            sb.append("定位失败" + "\n");
            sb.append("错误码:" + location.getErrorCode() + "\n");
            sb.append("错误信息:" + location.getErrorInfo() + "\n");
            sb.append("错误描述:" + location.getLocationDetail() + "\n");
        }
        lat = location.getLatitude();
        lng = location.getLongitude();
        saveAddr(location.getCity());

        return sb.toString();
    }

    private void saveAddr(final String city) {
        if (TextUtils.isEmpty(city)) {
            return;
        }
        if (!city.equals(AppContext.myPreferences.getCityLocation())) {
            AppContext.myPreferences.setCityLocation(city);
            if (SelectCityActivity.onCityLocation != null)
                SelectCityActivity.onCityLocation.onCity(city);
        }

        if (TextUtils.isEmpty(AppContext.myPreferences.getCity()) || TextUtils.isEmpty(AppContext.myPreferences.getCityId())) {
            AppContext.myPreferences.setCity(city);
            getCityId(city);
            return;
        }

        if (!city.equals(AppContext.myPreferences.getCity())) {
            if (MainActivity.onCityChanged != null) {
                MainActivity.onCityChanged.onCity(city);
            }
        }
    }

    private void getCityId(final String city) {
        new GetCityId(city, new AsyCallBack<GetCityId.Info>() {
            @Override
            public void onSuccess(String toast, int type, GetCityId.Info info) throws Exception {

                AppContext.myPreferences.setCityId(info.cityid);
                if (OrderingFragment.onCityChanged != null)
                    OrderingFragment.onCityChanged.onCityChanged(city, info.cityid);

                if (MyStardandActivity.onCityChanged != null)
                    MyStardandActivity.onCityChanged.onCityChanged(city, info.cityid);
            }

            @Override
            public void onEnd(String toast, int type) throws Exception {

            }
        }).execute(AppContext.getContext());
    }

    public void recycleLocation(){
        if (null != locationClient) {
            locationClient.onDestroy();
            locationClient = null;
            locationOption = null;
        }
    }
}
